<template>
	<nt-container calcTabbar v-model="scrollHeight">
		<nt-tabs :list="tabs" @click="changeTabs" :current="orderTypeIndex" :loading="loading"></nt-tabs>

		<view class="staging-container">
			<!-- <nt-search></nt-search> -->
			<nt-search :showSelect="true" @sendPicker="getPicker" @search="search" v-if="showSearch"
				@input="getInput"></nt-search>
			<view class="order-map" @tap="openMap">
				我的订单地图
			</view>
			<template v-if="orderList.length >0">
				<u-list @scrolltolower="getMemberOrderList" @refresherrefresh="refresherrefresh" enableBackToTop
					refresher-enabled :refresher-triggered="isPull" refresher-background="#F2F4F6"
					refresher-threshold="50" :height="`${listHeight}px`">
					<template v-for="it in orderList">
						<view class="staging-item" v-if="[1, 2].includes(it.nav_status_text)" :key="it.id">
							<!-- 待上门显示 -->
							<view class="staging-item__arrive" v-if="it.nav_status_text == 2">
								<view class="staging-item__arrive--day">{{it.appointment | dayBriefFilter}}</view>
								<view class="staging-item__arrive--time">
									{{ it.appointment | interceptTimeFilter }}
									<view class="staging-item__arrive--service">上门</view>
								</view>
							</view>
							<nt-receiving-order :data="it" @click="toDetail(it)">
								<template #button>
									<view class="staging-btn__group">
										<nt-button text="接单" color="#2D7FFD" @tap="receiveOrderHandle(it)"
											v-if="it.nav_status_text == 1"></nt-button>
										<nt-button :text="setBtnText(it.step_status)" color="#2D7FFD" @tap="toDoor(it)"
											v-if="it.nav_status_text == 2"></nt-button>
										<nt-button v-if="it.is_apply_transfer !== 1" text="转单" color="#2D7FFD"
											@click="transitionOrder(it)"></nt-button>
										<nt-button
											v-if="it.powerStatus&&it.powerStatus.postSmsnotice&&it.powerStatus.postSmsnotice===1"
											text="发短信通知" color="#22D58D" @click="goNotice(it)"></nt-button>
									</view>
								</template>
							</nt-receiving-order>
						</view>
						<view class="staging-item" :key="it.id" v-else>
							<nt-order-item :data="it" @refresh="init"></nt-order-item>
						</view>
					</template>
					<button class="h_button" @click="getData">
						上传异常数据
					</button>
				</u-list>
			</template>
			<u-empty icon="https://cdn.uviewui.com/uview/empty/data.png" v-else></u-empty>
		</view>

		<view class="popmsgWarp" v-if="popmsgStorage.status">
			<view class="popmsgContent">
				<view class="popmsgBody">
					<view class="title">{{popmsgStorage.data.title}}</view>
					<view class="secondWarp"><text class="second">{{popmsgStorage.data.show_time}}</text>s自动关闭</view>
				</view>
			</view>
		</view>

		<u-modal :show="showTel" title="联系客户" content="请及时电话联系客户,确认预约时间" confirm-text="联系客户"
			@confirm="callPhone" ></u-modal>
	</nt-container>
</template>

<script>
	import dayjs from "dayjs"
	import {
		mapGetters,
		mapActions
	} from "vuex"
	import {
		getOrderList,
		receivingOrders,
		makingPhone,
		getCountTabs,
		indexData,
		magicFuntype
	} from "@/api"
	import {
		getCacheList,
		cache
	} from "@/utils"
	import {
		appConfig
	} from "../../config"
	import md5 from 'js-md5'
	export default {
		data() {
			return {
				popmsgStorage: {
					'data': {},
					status: 0,
					'timer': null
				},
				showTel: false,
				tabs: [{
						name: "待接单",
						value: '1'
					},
					{
						name: "待上门",
						value: "2"
					},
					{
						name: "维修中",
						value: "3"
					},
					// { name: "待提交", value: "4" },
					{
						name: "待完成",
						value: "5"
					},
					{
						name: "已完成",
						value: "6"
					},
					{
						name: "异常单",
						value: "7"
					},
				],
				params: {
					status_text: '1',
					page: 1,
					limit: 10,
					keyword: "",
					whereTime: ""
				},
				orderList: [],
				loading: false,
				current: 0,
				cureentOrder: {},
				isNext: true,
				scrollHeight: 0,
				showSearch: false,
				isPull: false,
				md5: ''
			}
		},
		computed: {
			...mapGetters(['orderTypeIndex', 'indexCache', 'userInfo']),
			listHeight() {
				let convention = this.scrollHeight - 100;
				if (this.showSearch) {
					convention -= 100
				}
				return convention
			}
		},
		watch: {
			orderTypeIndex: {
				handler(nv) {
					this.params.status_text = this.tabs[nv].value
				},
				immediate: true
			}
		},
		onLoad(options) {
			const that = this
			if (options.status) {
				that.params.status_text = options.status
			}
			that.time = new Date().getTime()
			that.rest()
			that.getLocalData()
			that.getMemberOrderList(that.time)
			that.$nextTick(() => that.getOrderCount())
			uni.$on('changeList', () => {
				that.time = new Date().getTime()
				that.rest()
				that.getLocalData()
				that.getMemberOrderList(that.time)
				that.$nextTick(() => that.getOrderCount())
			})
			that.getPopmsgAlert()
		},
		methods: {
			getInput(e) {
				this.params.keyword = e
			},
			openMap() {
				// #ifdef APP-PLUS
				const {
					token,
					user_id
				} = this.userInfo
				const md5Token = md5(token + user_id)
				plus.runtime.openURL(
					`https://m.nantianit.com/index/index/eventtype?token=${md5Token}&user_id=${user_id}&eventtype=myordermap`,
					function(res) {
						console.log(res);
					});
				// #endif
			},
			getPicker(e) {
				this.params.queryType = e.value
				this.init()
			},
			getPopmsgAlert() {
				try {
					this.popmsgStorage.data = uni.getStorageSync('popmsgStatus');
					if (this.popmsgStorage.data) {
						this.popmsgStorage.data = JSON.parse(this.popmsgStorage.data);
					} else {
						this.popmsgStorage.data = {};
					}
					let nowTime = new Date();
					if (JSON.stringify(this.popmsgStorage.data) === "{}" || this.popmsgStorage.data.end_time < nowTime
						.getTime() / 1000) {
						magicFuntype('corpus/popmsg').then(result => {
							if (result.data.length) {
								let it = result['data'][0];
								it.end_time = nowTime.getTime() / 1000 + it.out_time;
								this.popmsgStorage.data = it;
								this.popmsgStorage.status = 1;
							} else {
								this.popmsgStorage.status = 0;
								this.popmsgStorage.data = {};
							}
							if (this.popmsgStorage.status) {
								this.timerFuntype()
							}
							uni.setStorageSync('popmsgStatus', JSON.stringify(this.popmsgStorage.data));
						})
					}
				} catch (e) {
					// error
				}
			},
			timerFuntype(funtype = '') {
				if (funtype == 'clear') {
					clearInterval(this.popmsgStorage.timer)
					this.popmsgStorage.timer = null
					this.popmsgStorage.status = 0
				} else {
					this.popmsgStorage.timer = setInterval(() => {
						if (this.popmsgStorage.data.show_time <= 0) {
							clearInterval(this.popmsgStorage.timer)
							this.popmsgStorage.timer = null
							this.popmsgStorage.status = 0
						} else {
							this.popmsgStorage.data.show_time--;
						}
					}, 1000)
				}
			},
			getData() {
				let thisData = this.$data;
				let postData = {
					"path": "/pages/staging/index.vue",
					"data": thisData
				}
				console.log(postData)
				indexData(postData).then(res => {
					console.log(res)
				})
			},
			getLocalData() {
				if (this.indexCache) {
					const {
						list,
						md5
					} = getCacheList('staging', this.params.status_text)
					this.orderList = list || []
					this.md5 = md5 || ''
				}
			},
			onNavigationBarButtonTap() {
				this.showSearch = !this.showSearch
			},
			refresherrefresh() {
				this.isPull = true
				this.init()
			},
			getOrderCount() {
				getCountTabs("worker_order").then(res => {
					if (res.code === 1 && res.data) {
						const ntabs = JSON.parse(JSON.stringify(this.tabs))
						Object.entries(res.data).map(([key, value]) => {
							this.tabs = ntabs.map((item) => {
								if (key == Number(item.value)) {
									if (value > 0) {
										item.badge = {
											value: value
										}
									} else {
										item.badge = undefined
									}
								}
								return item
							})
						})
					}

				})
			},
			// 获取订单列表
			getMemberOrderList(time) {
				if (this.loading || !this.isNext) return;
				getOrderList(this.params).then(res => {
					const {
						code,
						data,
						md5
					} = res;
					if (this.time === time) {
						if (this.params.page === 1 && this.indexCache) {
							console.log('indexCache')
							const cData = cache.get.staging() || {}
							cData[this.params.status_text] = {
								md5,
								list: JSON.parse(JSON.stringify(data.data)),
								expireTime: Date.now() + appConfig.listDataExpireTime
							}
							cache.set.staging(cData)
							this.orderList = []
						}
						this.orderList = this.orderList.concat(data.data);
						this.params.page++
						if (this.orderList.length >= data.total) {
							this.isNext = false
						}
					}
				}).catch(err => {
					console.log(err, '错误')
				}).finally(() => {
					this.loading = false
					setTimeout(() => {
						this.isPull = false
					}, 500)
				})
			},
			// 接单
			receiveOrderHandle(data) {
				// if(this.loading) return;
				// this.loading = true;
				this.cureentOrder = data
				receivingOrders(data.id).then(async res => {
					const {
						code,
						data
					} = res;
					this.loading = false;
					if (code === 1) {
						this.toast("接单成功")
						if (this.cureentOrder.is_type == '维修') {
							this.$store.commit("app/SET_ORDER_TYPE_INDEX", 1)
							this.params.status_text = "2"
							await this.init()
							await this.getOrderCount()
						} else {
							await this.init()
							await this.getOrderCount()
							uni.switchTab({
								url: '/pages/repatriation/index'
							});
						}
						// this.$nextTick(() => this.getOrderCount())
						// this.toast("接单成功")
						// this.$store.commit("app/SET_ORDER_TYPE_INDEX", 1)
						// this.params.status_text = 2
						// this.init()
					}
				}).catch(err => {
					this.loading = false;
				})
			},
			// 拨打电话
			callPhone() {
				const {
					id,
					customerphone
				} = this.cureentOrder
				makingPhone(id).then(res => {
					const {
						code,
						data
					} = res;
					if (code !== 1) return this.toast("拨打电话失败");
					this.showTel = false;
					this.init()
					setTimeout(() => this.makePhoneCall(customerphone))
				}).catch(err => {
					this.toast("拨打电话失败")
				})
			},
			// 上门
			toDoor(it) {
				this.cureentOrder = it
				if (it.step_status === 2) {
					this.showTel = true;
					return;
				} else if (it.step_status === 3) {
					this.nav(`/subpackage/order/pages/reservation/index?id=${it.id}`)
					return;
				} else if (it.step_status === 4) {
					this.nav(
						`/subpackage/order/pages/scan-code/index?id=${it.id}&customername=${it.customername}&customerphone=${it.customerphone}&address=${it.address}&qrCode=${it.present_images}`
					)
					return
				} else if (it.step_status === 5) {
					this.nav(`/subpackage/order/pages/submit/recovery?id=${it.id}`)
				}
			},
			// 转单
			transitionOrder(it) {
				if (it.is_apply_transfer === 1) return this.toast("转单中，不可重复提交");
				this.nav(`/subpackage/order/pages/submit/form?id=${it.id}&mode=transfer`)
			},
			// 通知
			goNotice(it) {
				this.nav(`/subpackage/order/pages/submit/form?id=${it.id}&mode=notice`)
			},
			// 查看订单详情
			toDetail(it) {
				if (it.nav_status_text == "1") return;
				this.nav(`/subpackage/order/pages/detail?id=${it.id}`)
			},
			async changeTabs(item) {
				if (item.index === this.orderTypeIndex) return;
				if (this.loading) return;
				this.params.status_text = item.value
				this.$store.commit("app/SET_ORDER_TYPE_INDEX", item.index)
				this.params.keyword = "";
				this.params.whereTime = "";
				this.showSearch = false;
				this.rest()
				this.getLocalData()
				this.time = new Date().getTime()
				await this.getMemberOrderList(this.time)
				await this.getOrderCount()

			},
			rest() {
				this.orderList = []
				this.params.page = 1
				this.params.limit = 10
				this.isPull = false
				// this.params.keyword = ""
				this.isNext = true;
			},
			init() {
				this.rest();
				this.time = new Date().getTime()
				this.getMemberOrderList(this.time)
			},
			setBtnText(step) {
				if (step === 2) {
					return "联系客户"
				} else if (step === 4) {
					return "上门"
				} else if (step === 3) {
					return "预约时间"
				} else if (step === 5) {
					return '维修报价'
				}
			},
			search(e) {
				this.params.keyword = e.keyword
				if ((e.startTime && e.endTime) && (e.startTime > e.endTime)) return this.toast("开始时间不能大于结束时间")
				if (e.startTime || e.endTime) {
					let startTime = e.startTime ? dayjs(e.startTime).format("YYYY-MM-DD") : ""
					let endTime = e.endTime ? dayjs(e.endTime).format("YYYY-MM-DD") : ""
					this.params.whereTime = `${startTime},${endTime}`
				}
				this.init()
			}
		},
		onPullDownRefresh() {
			this.time = new Date().getTime()
			this.getMemberOrderList(this.time)
			// setTimeout(function () {
			uni.stopPullDownRefresh();
			// }, 1000);
		}
	}
</script>

<style lang="scss" scoped>
	.popmsgWarp {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100vh;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
		align-content: center;
	}

	.popmsgWarp .popmsgContent {
		padding: 1rem;
		max-width: 100%;
	}

	.popmsgWarp .popmsgBody {
		padding: 2rem;
		border-radius: 11px;
		background: #fff;
		color: #999;
	}

	.popmsgWarp .title {
		font-size: 16px;
		color: #333;
	}

	.popmsgWarp .second {
		color: #f00;
		font-size: 28px;
	}

	.popmsgWarp .secondWarp {
		text-align: center;
	}

	.staging {
		&-container {
			box-sizing: border-box;

			/deep/ .receiving-container {
				margin-bottom: 40rpx;
			}

			/deep/ .u-list {
				padding: 20rpx;
				box-sizing: border-box;
			}
		}

		&-item {
			&__arrive {
				color: #333;
				font-size: 32rpx;
				font-weight: bold;
				padding: 20rpx 0;

				&--time {
					display: flex;
					align-items: center;
				}

				&--service {
					color: #666;
					font-size: 28rpx;
					font-weight: normal;
					margin-left: 10rpx;
				}
			}
		}

		&-btn {
			&__group {
				margin-top: 40rpx;

				/deep/ .button-container+.button-container {
					margin-top: 30rpx;
				}
			}
		}
	}

	.order-map {
		line-height: 50px;
		text-align: center;
		background-color: #fff;
		color: var(--theme-color);
		border-top: 0.5px solid rgb(242, 244, 246);
	}
</style>